import type { IPermission } from "@/apis/acl/menu/type";

/**
 * 将权限数组转换成树形结构
 * @param dataList
 * @returns
 */
export function listToTree(
  list: IPermission[],
  rootId?: string
): IPermission[] {
  // 找到根节点ID
  rootId = rootId || findParentId(list);

  // 将列表转换为树
  return list.reduce((prev: IPermission[], curr: IPermission, _, arr) => {
    // 设置子节点
    curr.children = arr.filter(item => item.pid === curr._id);
    // 如果当前节点是根节点，将其添加到结果数组中
    if (curr.pid === rootId) {
      prev.push(curr);
    }
    // 删除当前节点的 pid 和 level 属性
    delete curr.pid;
    delete curr.level;

    // 返回修改后的结果数组
    return prev;
  }, [] as IPermission[]);
}
// export function listToTree(list: IPermission[], rootValue?: string) {
//   rootValue = rootValue || findParentId(list);
//   return list.reduce((prev, curr, _, arr) => {
//     curr.children = arr.filter(item => item.pid === curr._id);
//     if (curr.pid === rootValue) {
//       prev.push(curr);
//     }
//     delete prev[prev.length - 1].pid;
//     delete prev[prev.length - 1].level;

//     return prev;
//   }, [] as IPermission[]);
// }

/**
 * 树形转平面数组
 * @param data 树形结构数组
 * @returns
 */
export function TreeToList(data: IPermission[]) {
  let newArr: IPermission[] = [];
  const action = (data: IPermission[]) => {
    data.forEach(item => {
      newArr.push(item);
      if (!!item.children) {
        item.children.forEach(i => {
          i.pid = item._id;
          i.level = item.level! + 1;
        });
        action(item.children);
      }
      delete item.children;
    });
  };
  action(data);
  return newArr;
}

export function handlePermissions(list: IPermission[], perIds: string[]) {
  return list.map(i => {
    return {
      ...i,
      select: perIds.includes(i._id!) ? true : false,
    };
  });
}

/**
 * 查找父节点的_id
 * @param list
 * @returns
 */
export function findParentId(list: IPermission[]) {
  return list.find(i => i.level === 1 && i.pid === "")?._id as string;
}

/**
 * 时间戳格式化
 * @param date 日期
 */
export const dateFormat = (dateStr: string) =>
  new Date(dateStr).toLocaleString();

/**
 * 判断两数组是否相等
 * @param a
 * @param b
 * @returns
 */
export const arrEquation = (a: any[], b: any[]) => {
  if (a.length !== b.length) return false;
  return !a.some(i => !b.includes(i));
};

/**
 * 判断是否为空对象
 * @param obj
 * @returns
 */
export const isEmpty = (obj: object) => Object.keys(obj).length === 0;

/**
 * 深拷贝
 * @param value
 * @returns
 */
export function clone<T>(value: T): T {
  /** 空 */
  if (!value) return value;
  /** 数组 */
  if (Array.isArray(value)) {
    return value.map(item => clone(item)) as unknown as T;
  }
  /** 日期 */
  if (value instanceof Date) {
    return new Date(value) as unknown as T;
  }
  /** 普通对象 */
  if (typeof value === "object") {
    return Object.fromEntries(
      Object.entries(value).map(([k, v]: [string, any]) => {
        return [k, clone(v)];
      })
    ) as unknown as T;
  }
  /** 基本类型 */
  return value;
}
